package ooo.reindeer.data.decoder;

import io.netty.buffer.ByteBuf;

import java.io.InputStream;

public class FixedLengthFrameDecoder implements IFrameDecoder {

    private final int frameLength;

    /**
     * Creates a new instance.
     *
     * @param frameLength
     *         the length of the frame
     */
    public FixedLengthFrameDecoder(int frameLength) {
        if (frameLength <= 0) {
            throw new IllegalArgumentException(
                    "frameLength must be a positive integer: " + frameLength);
        }
        this.frameLength = frameLength;
    }

    public ByteBuf decode(ByteBuf in, InputStream inputStream) throws Exception {
        while (in.readableBytes() < frameLength) {
            in.writeBytes(inputStream, this.frameLength);
        }
        return in.readRetainedSlice(frameLength);

    }
}